// UserServiceImpl.java
package com.chixing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.entity.User;
import com.chixing.mapper.UserMapper;
import com.chixing.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chixing.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public User getUserByPhone(String phone) {
        return getOne(new QueryWrapper<User>().eq("phone", phone));
    }

    @Override
    public boolean register(User user) {
        // 检查手机号是否已注册
        User existingUser = getOne(new QueryWrapper<User>().eq("phone", user.getPhone()));
        if (existingUser != null) {
            return false;
        }
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        // 设置注册时间
        user.setRegisterTime(java.time.LocalDateTime.now());
        user.setStatues(1); // 正常状态
        return save(user);
    }
    // 在 UserServiceImpl 中添加修复方法
    @Override
    public void resetUserPassword(String phone, String newPassword) {
        User user = getOne(new QueryWrapper<User>().eq("phone", phone));
        if (user != null) {
            // 使用 BCryptPasswordEncoder 加密密码
            user.setPassword(passwordEncoder.encode(newPassword));
            updateById(user);
        }
    }


    @Override
    public String login(String phone, String password) {
        // 查询用户
        User user = getOne(new QueryWrapper<User>().eq("phone", phone));
        if (user == null) {
            return null; // 用户不存在
        }
        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return null; // 密码错误
        }
        // 生成JWT
        return jwtUtils.generateToken(user.getUserId());
    }
    // 在UserService中添加refresh token存储逻辑
    public void storeRefreshToken(Integer userId, String refreshToken) {
        // 使用Redis存储，设置与token相同的过期时间
        redisTemplate.opsForValue().set(
                "refresh_token:" + userId,
                refreshToken,
                30, TimeUnit.DAYS
        );
    }

}
